/**
 *  任务切水果模式
 */
class TaskCustomsUI extends UIBase{
    // private mPoints: any[];
    // private mPenSize: number = 4;
    private mPrev: number;
    private mIsDown: boolean;

    private mMS: number = 330;
    private mStartTime:number;
    private mItems:fruit[] = [];
    private fruit_group:eui.Group;
    private timer:number;
    private count= 0;
    private lb_time:eui.Label;
    private isGameOver:boolean = false;
    private fruitCnt = 0;

    private killNum:number = 0;
    private mask_group:eui.Group;
    private lb_start:eui.Label;
    private touchId;
    private system:particle.ParticleSystem;
    private aimFruitId:number = 0;
    private fruitList = [];
    private aimNum = 0;
    private lb_num:eui.Label;
    private img_fruit:eui.Image;
    private btn_home:BaseButton;
    private img_ok:eui.Image;
    private lb_curNum:eui.Label;
    private btn_sure:BaseButton;
    private lb_fruit:eui.Label;
    private group_state:eui.Group;

    private isjump:boolean = false;
    private img_prepare:eui.Image;

    constructor()
    {
        super('TaskCustomsView');
    }

    public init()
    {
        super.init(true);
        this.fruitList = [];
        this.mItems = [];
        let curCustoms = GameManager.instance.curCustoms;
        let per = DataJson.const_define.task_customs.award;
        let totalNum = GameConst.task_customs_total_num;
        let customs = (Math.floor((curCustoms/per)) % totalNum);
        let customsData = DataJson.taskCustoms_define[customs];
        if(customsData)
        {
            this.aimFruitId = customsData.aim_fruit;
            let str = customsData.list;
            let fruitList = str.split(',');
            this.aimNum = customsData.num;
            for(let v of fruitList)
            {
                if(v == this.aimFruitId+'')
                {
                    fruitList.splice(fruitList.indexOf(v),1);
                }
            }
            this.fruitList = fruitList;
            let fruit_data = DataJson.fruit_data[this.aimFruitId];
            this.lb_fruit.text = StringUtil.getSwfLangStrVar('task_1', [fruit_data.name, this.aimNum]);
        }
        this.lb_num.text = `x${this.aimNum}`;
        this.img_fruit.source = 'fruit_full_'+this.aimFruitId;
        let sprite1: egret.Shape = new egret.Shape();
        let sprite: egret.Shape = new egret.Shape();
        this.addChild( sprite1 );
        this.addChild( sprite );
        this.lb_curNum.text = '';

        this.mPrev = 0;
        this.timer = 30;
        this.mStartTime = egret.getTimer();
        this.mMS = 330;
        if(customs >= 15)
        this.mMS = 250;

        this.mask_group.visible = true;
        this.addParticle();
    }

    public addParticle()
    {
        let texture = RES.getRes('particle_18');
        let config = RES.getRes('particle_52_json');
        this.system = new particle.GravityParticleSystem(texture, config);
        this.fruit_group.addChildAt(this.system,0);
        this.system.emitterX = 0;
        this.system.emitterY = 0;
    }

    public cutAllFruit()
    {
        let list = this.mItems;
        for(let i in list)
        {
            let fruit = list[i] as fruit;
            let fruitData = fruit.Data;
            let data = {
                id:fruitData.id,
                color:fruitData.color
            }
            let item = fruitBoomItem.getBoomItem(data);
            if(!this.fruit_group.contains(item))
            this.fruit_group.addChildAt(item,1);
            item.x = fruit.x;
            item.y = fruit.y;
            item.boom(fruit.killed, fruit);
        }
        this.GameOver();
    }

    public updateTime()
    {
        if(this.isGameOver)return;
        let time = this.timer;
        this.lb_time.text = `倒计时:${time}`;
        if(time <= 3)
        {
            this.lb_time.scaleX = this.lb_time.scaleY = 50;
        }
        egret.Tween.get(this.lb_time).to({
            scaleX:1,
            scaleY:1
        }, 300);
    }

    public addEvent()
    {
        this.fruit_group.addEventListener( egret.TouchEvent.TOUCH_BEGIN,this.onTouchBeginHandler,this );
        this.fruit_group.addEventListener( egret.TouchEvent.TOUCH_MOVE,this.onTouchMoveHandler,this );
        this.fruit_group.addEventListener( egret.TouchEvent.TOUCH_END,this.onTouchEndHandler,this );
        this.btn_home.addTapHandler(this.backHome, this);
        this.btn_sure.addTapHandler(this.startGame, this);
        // egret.startTick( this.onLoopHandler,this );
    }

    public startGame()
    {
        this.group_state.visible = false;
        this.img_prepare.scaleX = this.img_prepare.scaleY = 1.5;
        this.img_prepare.alpha = 1;
        SoundManager.instance().playSound('ready_go');
        egret.Tween.get(this.img_prepare).to({
            scaleX:1,
            scaleY:1,
            alpha:1
        }, 600, egret.Ease.backIn).wait(400).set({
            source:'img_go_png'
        }).to({
            alpha:0,
            scaleX:0,
            scaleY:0
        }, 700, egret.Ease.backIn).call(this.gameStart, this);
    }

    public gameStart()
    {
        this.mask_group.visible = false;
        egret.startTick( this.onLoopHandler,this );
    }

    public backHome()
    {
        this.isjump = true;
        ScreenMovies.MovieStart(2,()=>{
            let da = {
                index:0
            }
            UIManager.instance().openUILogic(MainUI, da);
        },this);
    }

    private onLoopHandler(t:number):boolean
	{
        if(!this.mItems)return;
        this.count++;
        if(this.count % 60 == 0)
        {
            this.timer--;
            this.count = 0;
            this.updateTime();
        }
        if(this.timer <= 0 && !this.isGameOver)
        {
            this.GameOver();
        }

        let cutTime = egret.getTimer();
        if(cutTime - this.mStartTime >= this.mMS)
        {
            this.createItems();
            this.mStartTime = cutTime;
        }
        let _count: number = this.mItems.length;
        if( _count ){
            for( let i: number = 0;i < _count;i ++){
                let fruit: fruit = this.mItems[i];
                fruit.action();
                if( fruit.y > this.fruit_group.height + 20 ){
                    this.mItems.splice( i,1 );
                    FruitPool.pushFruit(fruit);
                    _count = this.mItems.length;
                    i--;
                }
            }
        }
        return false;
	}

    public rePlay()
    {
        this.group_state.visible = true;
        this.img_prepare.source = 'img_ready_png';
        this.lb_time.text = `倒计时:30`;
        egret.stopTick( this.onLoopHandler,this );
        this.clearData();
        let self = this;
        egret.setTimeout(()=>{
            self.init();
        },this, 500);
    }

    public GameOver()
    {
        this.isGameOver = true;
        if(this.system)
        {
            this.system.stop();
        }
        let data = {
            isPop:true,
            effect:1
        }
        UIManager.instance().openUILogic(TaskFailUI, data);
    }

    public getFruit(id)
    {
        let data = DataJson.fruit_data[id];
        let fruit = FruitPool.getFruit(data);
        return fruit;
    }

    public getFruit2(id)
    {
        let data = JSON.parse(JSON.stringify(DataJson.fruit_data[id]));
        data.isLight = true;
        let fruit = FruitPool.getFruit(data);
        return fruit;
    }

    private createItems()
    {
        let fruitNum = this.fruitList.length;
        let gailv = GameManager.instance.curCustoms >= 30 ? 0.15 : 0.25
        let fruit_id = Math.random() > 0.25 ? this.aimFruitId : this.fruitList[Math.floor(Math.random() * fruitNum)];
        let fruit: fruit
        if(fruit_id == this.aimFruitId)
        {
            // this.setCurItem(fruit)
            fruit = this.getFruit2(fruit_id);
        }
        else
        {
            fruit = this.getFruit(fruit_id);
        }
        if(!this.fruit_group.contains(fruit))
        this.fruit_group.addChildAt( fruit ,0);

        let rand: number = Math.floor( Math.random() * 3 );
        fruit.born();
        let flag: number = Math.random() > 0.5 ? 1 : -1;
        fruit.x = this.width / 2 + flag * Math.random() * 250;
        fruit.y = this.fruit_group.height + 30;
        this.mItems.push( fruit );
    }

    private onTouchBeginHandler( e:egret.TouchEvent):void
    {
        this.touchId = e.touchPointID;
        this.mIsDown = true;
        let _x: number = e.stageX;
        let _y: number = e.stageY;
        if(this.system)
        {
            this.system.start();
            this.system.visible = true;
            this.system.emitterX = _x;
            this.system.emitterY = _y;
        }
    }

    private onTouchMoveHandler( e:egret.TouchEvent):void
    {
        if(this.touchId != e.touchPointID)
        {
           return;
        }
        if( this.mIsDown && !this.isGameOver){
            let _x: number = e.stageX;
            let _y: number = e.stageY;
            if(this.system.visible)
            {
                this.system.emitterX = _x;
                this.system.emitterY = _y;
            }
            let _count: number = this.mItems.length;
            for( let i = 0;i < _count;i++){
                let fruit: fruit = this.mItems[i];
                if(( _x > (fruit.x - fruit.width / 2) ) && ( _x < (fruit.x + fruit.width / 2) )
                    && ( _y > (fruit.y - fruit.height / 2) ) && ( _y < (fruit.y + fruit.height / 2) )){//可以切

                    let fruitData = fruit.Data;
                    if(fruitData.id == this.aimFruitId)
                    {
                        this.killNum ++;
                        this.updateNum();
                    }
                    else
                    {
                        this.GameOver();
                    }
                    let data = {
                        id:fruitData.id,
                        color:fruitData.color
                    }

                    this.mItems.splice( i,1 );
                    _count = this.mItems.length;
                    i--;
                    this.fruitCnt++;

                    //添加爆炸效果
                    let item = fruitBoomItem.getBoomItem(data);
                    if(!this.fruit_group.contains(item))
                    this.fruit_group.addChildAt(item,1);
                    item.x = fruit.x;
                    item.y = fruit.y;
                    item.boom(fruit.killed, fruit);
                    WeChatgGameManager.instance().vibrateShort();
                }
            }
        }
    }

    public updateNum()
    {
        this.lb_curNum.text = `X${this.killNum}`;
        if(this.killNum == this.aimNum)
        {
            this.img_ok.visible = true;
            this.win();
        }
    }

    public win()
    {
        this.isGameOver = true;
        this.system.stop();
        this.system.visible = false;
        let data  = {
            customs:GameManager.instance.curCustoms,
        }
        AccountPrase.instance().task_account(data);
    }

    // public setCurItem(fruit)
    // {
    //     if(!fruit)return;
    //     var color:number = 0x33CCFF;        /// 光晕的颜色，十六进制，不包含透明度
    //     var alpha:number = 0.8;             /// 光晕的颜色透明度，是对 color 参数的透明度设定。有效值为 0.0 到 1.0。例如，0.8 设置透明度值为 80%。
    //     var blurX:number = 35;              /// 水平模糊量。有效值为 0 到 255.0（浮点）
    //     var blurY:number = 35;              /// 垂直模糊量。有效值为 0 到 255.0（浮点）
    //     var strength:number = 2;            /// 压印的强度，值越大，压印的颜色越深，而且发光与背景之间的对比度也越强。有效值为 0 到 255。暂未实现
    //     var quality:number = egret.BitmapFilterQuality.HIGH;        /// 应用滤镜的次数，建议用 BitmapFilterQuality 类的常量来体现
    //     var inner:boolean = false;            /// 指定发光是否为内侧发光，暂未实现
    //     var knockout:boolean = false;            /// 指定对象是否具有挖空效果，暂未实现
    //     var glowFilter:egret.GlowFilter = new egret.GlowFilter( color, alpha, blurX, blurY,
    //         strength, quality, inner, knockout );
    //     fruit.filters = [ glowFilter ];
    // }

    // public clearCurItem(fruit)
    // {
    //     if(fruit)
    //     {
    //         fruit.filters = null;
    //     }
    // }

    private onTouchEndHandler( e:egret.TouchEvent):void
    {
        if(this.touchId != e.touchPointID)
        return;
        this.mIsDown = false;
        let _x: number = e.stageX;
        let _y: number = e.stageY;
        if(this.system)
        {
            this.system.stop();
            this.system.emitterX = _x;
            this.system.emitterY = _y;
        }
    }

    public removeEvent()
    {
        egret.stopTick( this.onLoopHandler,this );
        this.btn_home.removeTapHandler();
        this.btn_sure.removeTapHandler();
        this.fruit_group.removeEventListener( egret.TouchEvent.TOUCH_BEGIN,this.onTouchBeginHandler,this );
        this.fruit_group.removeEventListener( egret.TouchEvent.TOUCH_MOVE,this.onTouchMoveHandler,this );
        this.fruit_group.removeEventListener( egret.TouchEvent.TOUCH_END,this.onTouchEndHandler,this );
    }

    public clearData()
    {
        this.isGameOver = null;
        if(!this.mItems)return;
        for(let v of this.mItems)
        {
            v.remove();
        }
        this.mItems = null;
        this.fruit_group.removeChildren();
        this.mIsDown = null;

        this.mMS = null;
        this.mStartTime = null;
        this.timer = null;
        this.count = null;
        this.fruitCnt = null;
        this.killNum = null;
        if(this.system)
        {
            this.system.stop();
            this.system = null;
        }

        FruitPool.clearPool();
        fruitBoomItem.clearPool();
        
        this.touchId = null;
    }

    public clear()
    {
        super.clear();
        this.clearData();
        if(!this.isjump)
        UIManager.instance().openUILogic(GameUI);
        this.isjump = null;
    }
}